<template>
  <div class="view-fill">
    <div v-if="!showModify.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :btn-list="btnList"
        :title="title"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('deviceMaintenanceTaskDetail:print')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button v-if="canPrint" @click="print">打印</el-button> -->
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canReceiveOrder" @click="receiveOrder"
            >接单</el-button
          >
          <el-button v-if="canTurnOver" @click="turnOver">转交</el-button>
          <!-- <el-button v-if="canMountingsUse" @click="mountingsUse"
            >配件使用</el-button
          >
          <el-button v-if="canHandleMaintenance" @click="handleMaintenance"
            >养护执行</el-button
          > -->
          <el-button v-if="canFinish" @click="finish">执行</el-button>
          <el-button v-if="canCancel" @click="cancel">取消</el-button>
        </template>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>基础信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="baseInfoList">
              <template v-slot:basic-remindTime>
                <div v-if="baseInfoList.data.remindTime">
                  {{
                    '任务开始前' +
                    baseInfoList.data.remindTime +
                    baseInfoList.data.remindValue
                  }}
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>资产信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="assetInfoList"></basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>养护信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="deviceMaintenanceInfoList"
              ><template v-slot:basic-filePathList>
                <div v-if="deviceMaintenanceInfoList.data.filePathList">
                  <EleGallery
                    v-if="deviceMaintenanceInfoList.data.filePathList"
                    :lazy="true"
                    :size="150"
                    :source="deviceMaintenanceInfoList.data.filePathList"
                    title="附件"
                  />
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="配件使用"
                  name="first"
                >
                  <!-- 表格 -->
                  <page-table
                    v-if="activeName === 'first'"
                    :refresh="tableInfo.refresh"
                    :init-curpage="tableInfo.initCurpage"
                    v-model:data="tableInfo.data"
                    :query="tableInfo.query"
                    :api="tableInfo.api"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :field-list="tableInfo.fieldList"
                    :isDynamic="true"
                  >
                  </page-table>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="养护项目"
                  name="second"
                >
                  <!-- 表格 -->
                  <el-form
                    ref="tableForm"
                    :model="itemsTableInfo"
                    style="width: 100%"
                  >
                    <page-table
                      v-if="activeName === 'second'"
                      :refresh="itemsTableInfo.refresh"
                      :init-curpage="itemsTableInfo.initCurpage"
                      v-model:data="itemsTableInfo.data"
                      :api="itemsTableInfo.api"
                      :pager="false"
                      :check-box="false"
                      :tab-index="true"
                      :query="itemsTableInfo.query"
                      :field-list="itemsTableInfo.fieldList"
                      :handle="itemsTableInfo.handle"
                      :isDynamic="true"
                      @handleEvent="handleEvent"
                    />
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>

        <div class="model-panel model-panel-right">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="clickName" @tab-click="handleTabClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="基本信息"
                  name="first"
                >
                  <basic-information :info="basicInfoList">
                  </basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="操作流水"
                  name="second"
                >
                  <Timeline :list="affairTableInfo.data" />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
        <chose-printer
          :visible="printerInfo.visible"
          @callBack="handlePrinterCallBack"
        />
      </NewFullScreen>
    </div>
    <Modify
      v-if="showModify.visible"
      :id="id"
      v-model:visible="showModify.visible"
      :title="showModify.title"
      @returnModify="modifyCallback"
    ></Modify>
    <TurnOver
      v-if="turnOverInfo.visible"
      v-model:visible="turnOverInfo.visible"
      :row="turnOverInfo.row"
      @callbackTurnOver="callbackTurnOver"
    />
    <MountingsUse
      v-if="mountingsUseInfo.visible"
      v-model:visible="mountingsUseInfo.visible"
      :row="mountingsUseInfo.row"
      @callbackMountingsUse="callbackMountingsUse"
    />
    <Finish
      v-if="finishInfo.visible"
      v-model:visible="finishInfo.visible"
      :row="finishInfo.row"
      @callbackFinish="callbackFinish"
    />
    <HandleMaintenance
      v-if="handleMaintenanceInfo.visible"
      v-model:visible="handleMaintenanceInfo.visible"
      :row="handleMaintenanceInfo.row"
      @callbackHandleMaintenance="callbackHandleMaintenance"
    />
  </div>
</template>

<script setup name="deviceMaintenancePlanDetails">
import BasicInformation from '@/components/BasicInformation/index'
import Timeline from '@/components/Timeline/index.vue'
import EleGallery from '@/components/UploadImgNew/eleGallery'
import UploadVideo from '@/components/UploadVideo/index'
import {
  workDeviceMaintenanceTask,
  cancelDeviceMaintenanceTask,
  getDeviceMaintenanceTaskAccessoriesCustomizeListAll,
  printDeviceMaintenanceTaskDetail,
  getDeviceMaintenanceTaskById,
  excelDeviceMaintenanceTaskDetail,
  getDeviceMaintenanceTaskProgramAll,
} from '@/api/repair'
import { assetCodePrint } from '@/api/core'
import PageTable from '@/components/PageTable'
import { orderOpAffairAll } from '@/api/affair'
import chosePrinter from '@/components/ChosePrinter'
import { fatchTemplateByCode } from '@/api/base'
import { getCustomizeSetting } from '@/api/customize'
import TurnOver from '@/views/repair/repairManage/deviceMaintenanceTask/turnOver.vue'
import MountingsUse from '@/views/repair/repairManage/deviceMaintenanceTask/mountingsUse.vue'
import Finish from '@/views/repair/repairManage/deviceMaintenanceTask/finish.vue'
import Modify from '@/views/repair/repairManage/deviceMaintenanceTask/modify.vue'
import HandleMaintenance from '@/views/repair/repairManage/deviceMaintenanceTask/handleMaintenance.vue'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id'])

const activeName = ref('first')
const clickName = ref('first')
const title = ref('养护任务详情')
const btnList = ref([])
const printerInfo = reactive({
  visible: false,
  data: {},
})
const turnOverInfo = reactive({
  visible: false,
  row: {},
})
const mountingsUseInfo = reactive({
  visible: false,
  row: {},
})
const finishInfo = reactive({
  visible: false,
  row: {},
})
const handleMaintenanceInfo = reactive({
  visible: false,
  row: {},
})
//基础信息
const baseInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '养护单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '养护类型',
      value: 'typeValue',
      type: 'text',
    },

    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },

    {
      label: '养护计划编号',
      value: 'maintenancePlanOrderNo',
      type: 'text',
    },
    {
      label: '计划执行日期',
      value: 'nextExecuteDate',
      type: 'text',
    },
    {
      label: '养护负责人',
      value: 'maintenancePrincipalValue',
      type: 'text',
    },
    {
      label: '提醒于',
      value: 'remindTime',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})
//资产信息
const assetInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '资产',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'preAssetCode',
      type: 'text',
    },
    {
      label: '规格',
      value: 'preStandard',
      type: 'text',
    },
    {
      label: 'SN',
      value: 'machineCode',
      type: 'text',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'text',
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'text',
    },
  ],
})
//养护信息
const deviceMaintenanceInfoList = reactive({
  data: [],
  fieldList: [
    // {
    //   label: '养护状态',
    //   value: 'statusValue',
    //   type: 'text',
    // },

    // {
    //   label: '养护负责人',
    //   value: 'maintenancePrincipalValue',
    //   type: 'text',
    // },
    {
      label: '完工日期',
      value: 'completeDate',
      type: 'text',
    },

    {
      label: '合计工时(h)',
      value: 'totalHours',
      type: 'text',
    },
    {
      label: '养护服务费',
      value: 'maintenanceAmount',
      type: 'text',
    },
    {
      label: '养护材料费',
      value: 'maintenanceMaterialsAmount',
      type: 'text',
      formatter: proxy.$fn.TripartiteMethodAsset,
    },
    {
      label: '费用合计',
      value: 'amount',
      type: 'text',
    },
    {
      label: '完工说明',
      value: 'completeRemark',
      type: 'popover',
    },

    {
      label: '完工图片',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
//基本信息
const basicInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '养护单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'text',
    },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'text',
    },
    {
      label: '创建时间',
      value: 'createTime',
      type: 'text',
    },
    {
      label: '最后更新人',
      value: 'updateUserName',
      type: 'text',
    },
    {
      label: '最后更新时间',
      value: 'updateTime',
      type: 'text',
    },
  ],
})
//配件使用
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: null,
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
  fieldList: [],
})
// 养护项目
const itemsTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getDeviceMaintenanceTaskProgramAll,
  data: [],
  query: {
    orderId: props.id,
  },
  fieldList: [
    {
      label: '养护部位',
      value: 'maintenanceParts',
    },
    {
      label: '养护内容与要求',
      value: 'contentRequire',
    },
    {
      label: '养护结果',
      value: 'resultValue',
    },
    {
      label: '备注',
      value: 'remark',
    },
  ],
})
// 操作流水
const affairTableInfo = reactive({
  data: [],
  query: {
    orderType: 63,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
// 过滤相关配置
const customFilterInfo = reactive({
  query: {
    queryMap: {
      id: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      // isAssetAchievesExcel: "true",
    },
  },
})
const showModify = reactive({
  title: '',
  type: 'update',
  visible: false,
  currentAccountingInterval: '',
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    // idNotIn: "",
  },
})
const filterInfo = reactive({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:print') &&
    baseInfoList.data.status !== 1
  )
})
const canExcel = computed(() => {
  return proxy.$permission('deviceMaintenanceTask:excelDetail')
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:update') &&
    baseInfoList.data.status === 1 &&
    baseInfoList.data.maintenancePlanOrderNo === null &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canReceiveOrder = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:receiveOrder') &&
    baseInfoList.data.status === 1 &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canTurnOver = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:turnOver') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 2) &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canMountingsUse = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:mountingsUse') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canHandleMaintenance = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:handleMaintenance') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canFinish = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:handleMaintenance') &&
    baseInfoList.data.status === 2 &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})
const canCancel = computed(() => {
  return (
    proxy.$permission('deviceMaintenanceTask:cancel') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 2) &&
    baseInfoList.data.maintenanceOrgId === undefined &&
    baseInfoList.data.maintenancePrincipal ===
      proxy.$store.state.user.userInfo.user.id
  )
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    filterInfo.query.queryMap.orderId.value = newVal
    tableInfo.query.queryMap.orderId.value = newVal
    affairTableInfo.query.orderId = newVal
    customFilterInfo.query.queryMap.id.value = newVal
    itemsTableInfo.query.orderId = newVal
    getDetails()
  },
  {
    immediate: true,
    deep: true,
  }
)

let obj = {
  unitName: {
    label: '计量单位',
    value: 'unitName',
    componentType: 'input',
    show: false,
    hidden: false,
  },
  preUnitValue: {
    label: '计量单位',
    value: 'preUnitValue',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})

getCustomize()

function handleMaintenance() {
  handleMaintenanceInfo.visible = true
  handleMaintenanceInfo.row = baseInfoList.data
}
function callbackHandleMaintenance() {
  handleMaintenanceInfo.visible = false
  getDetails()
}
//取消
function cancel() {
  cancelDeviceMaintenanceTask(baseInfoList.data.id).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}
//接单
function receiveOrder() {
  workDeviceMaintenanceTask(baseInfoList.data.id).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}
//转交
function turnOver() {
  turnOverInfo.visible = true
  turnOverInfo.row = baseInfoList.data
}
function callbackTurnOver() {
  turnOverInfo.visible = false
  getDetails()
}
//配件使用
function mountingsUse() {
  mountingsUseInfo.visible = true
  mountingsUseInfo.row = baseInfoList.data
}
function callbackMountingsUse() {
  mountingsUseInfo.visible = false
  getDetails()
}
//完工
function finish() {
  finishInfo.visible = true
  finishInfo.row = baseInfoList.data
}
function callbackFinish() {
  finishInfo.visible = false
  getDetails()
}
// 编辑
function update() {
  showModify.visible = true
  showModify.title = '修改养护任务'
}
function handleClick(tab) {
  const name = tab.paneName
  proxy.$nextTick(() => {
    if (name == 'first') {
      getTableList()
    } else if (name == 'second') {
      getItemsList()
    }
  })
}
function handleTabClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
  } else if (name == 'second') {
    getAffairList()
  }
}

function modifyCallback() {
  getDetails()
}

function printAssetCode() {
  const data = []
  data.push(baseInfoList.data.id)
  assetCodePrint(data).then((res) => {
    if (res && res.success) {
      printerInfo.visible = true
      printerInfo.data = res.data
    }
  })
}

function exportExcel() {
  excelDeviceMaintenanceTaskDetail(tableInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'deviceMaintenanceTaskDetail',
    deptId: props.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: props.id,
            orderId: props.id,
            orderNo: props.orderNo,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: props.id,
      orderId: props.id,
      orderNo: props.orderNo,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}

function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function returnBack() {
  emit('returnBack', false)
}
// 触发事件
function handleEvent(event, data) {
  console.log(event, data)
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}

function getAffairList() {
  orderOpAffairAll(affairTableInfo.query).then((resp) => {
    if (resp && resp.success) {
      affairTableInfo.data = resp.data
    }
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = assetInfoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function getDetails() {
  getDeviceMaintenanceTaskById(props.id).then((resp) => {
    if (resp && resp.success) {
      baseInfoList.data = resp.data
      assetInfoList.data = resp.data
      deviceMaintenanceInfoList.data = resp.data
      basicInfoList.data = resp.data
      if (resp.data.assetStatus === 1) {
        showFieldListItem(true, 'preUseDeptValue')
        showFieldListItem(false, 'depotName')
      } else if (resp.data.assetStatus === 3) {
        showFieldListItem(false, 'preUseDeptValue')
        showFieldListItem(true, 'depotName')
      }
      getAffairList()
      getTableList()
      getItemsList()
    }
  })
}
function getTableList() {
  proxy.$nextTick(() => {
    tableInfo.refresh = Math.random()
  })
}
function getItemsList() {
  proxy.$nextTick(() => {
    itemsTableInfo.refresh = Math.random()
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'deviceMaintenanceTaskAccessoriesList-com.slip.spd.entity.domain.device.maintenance.task.DeviceMaintenanceTaskAccessories',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      tableInfo.api = getDeviceMaintenanceTaskAccessoriesCustomizeListAll
      getTableList()
    }
  })
}
</script>
<style scoped lang="scss">
:deep(.el-tabs__header) {
  padding: 0 2px !important;
  box-sizing: border-box;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px !important;
}
.model-panel-left {
  width: 73%;
  float: left;
  margin-right: 10px;
}
.model-panel-right {
  width: 25%;
}
</style>
